package com.ruoyi.web.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DataTypeEnum;
import com.ruoyi.common.enums.ReportStatusEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.DocumentHandlerUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.RailwayBigmodelVo;
import com.ruoyi.web.domain.RailwayBigmodel;
import com.ruoyi.web.service.IRailwayBigmodelService;
import com.ruoyi.web.utils.WordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * tlga大模型
 */
@Api("tlga大模型")
@RestController
@RequestMapping("/bigmodel")
public class RailwayBigmodelController extends BaseController
{
    @Autowired
    private IRailwayBigmodelService railwayBigmodelService;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询tlga大模型列表
     */
    @ApiOperation("查询tlga大模型列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody RailwayBigmodelVo railwayBigmodelVo)
    {

        List<RailwayBigmodel> list = railwayBigmodelService.selectRailwayBigmodelList(railwayBigmodelVo);
        for (RailwayBigmodel railwayBigmodel : list) {
            railwayBigmodel.setFileName(StringUtils.substringAfterLast(Optional.ofNullable(railwayBigmodel.getFilePath()).orElse("/"), "/"));
            if(StringUtils.isNotEmpty(railwayBigmodel.getTrainType())) {
                String[] split = railwayBigmodel.getTrainType().split(",");
                List<String> trainArray = new ArrayList<>();
                for (String s : split) {
                    //训练类型  0-预训练 1-二次预训练 2-优化训练
                    if(s.equals("0")){
                        s = "预训练";
                    }else if(s.equals("1")) {
                        s = "二次预训练";
                    } else if (s.equals("2")) {
                        s = "优化训练";
                    }
                    trainArray.add(s);
                }
                railwayBigmodel.setTrainTypeString(String.join(",", trainArray));
            }
            railwayBigmodel.setMobile(railwayBigmodel.getTelephone());
            railwayBigmodel.setUser(railwayBigmodel.getCreateBy());

        }
        List<RailwayBigmodel> total = railwayBigmodelService.selectRailwayBigmodelListTotal(railwayBigmodelVo);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total.size());
        return rspData;
    }

    /**
     * 导出tlga大模型列表
     */
    @ApiOperation("导出tlga大模型")
    @PostMapping("/export")
    public void export(HttpServletResponse response, RailwayBigmodel railwayBigmodel)
    {
        Map<String,Object> dataMap = railwayBigmodelService.selectExportDataMap(railwayBigmodel);
        DataTypeEnum dataTypeEnum = DataTypeEnum.YFJSBA.getType().equals(String.valueOf(dataMap.get("type")).trim()) ? DataTypeEnum.YFJSBA : DataTypeEnum.SXYYBA;
        WordUtils.creater().exportWord(response,dataMap,dataTypeEnum);
    }

    /**
     * 获取tlga大模型详细信息
     */
    @ApiOperation("获取tlga大模型详细信息")
    @ApiImplicitParam(name = "id", value = "tlga大模型id", required = true)
    @GetMapping(value = "/info/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(railwayBigmodelService.selectRailwayBigmodelByID(id));
    }

    /**
     * 新增tlga大模型
     */
    @ApiOperation("新增tlga大模型")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody RailwayBigmodelVo railwayBigmodelVo)
    {
        if(ObjectUtils.isNotEmpty(railwayBigmodelVo.getUser()) && ObjectUtils.isNotEmpty(railwayBigmodelVo.getUser().getSecurityOrg())) {
            railwayBigmodelVo.getRailwayBigmodel().setSecurityOrg(railwayBigmodelVo.getUser().getQuerySecurityOrg());
            railwayBigmodelVo.getRailwayBigmodel().setSecurityOrgName(railwayBigmodelVo.getUser().getSecurityOrgName());
        }
        return railwayBigmodelService.insertRailwayBigmodel(railwayBigmodelVo.getRailwayBigmodel());
    }

    /**
     * 存档
     */
    @ApiOperation("存档")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody RailwayBigmodelVo railwayBigmodelVo)
    {
        if(ObjectUtils.isNotEmpty(railwayBigmodelVo.getUser()) && ObjectUtils.isNotEmpty(railwayBigmodelVo.getUser().getSecurityOrg())) {
            railwayBigmodelVo.getRailwayBigmodel().setTelephone(railwayBigmodelVo.getRailwayBigmodel().getMobile());
            railwayBigmodelVo.getRailwayBigmodel().setCreateBy(railwayBigmodelVo.getRailwayBigmodel().getUser());
            railwayBigmodelVo.getRailwayBigmodel().setUpdateBy(railwayBigmodelVo.getRailwayBigmodel().getUser());
        }
        int rows = railwayBigmodelService.updateRailwayBigmodel(railwayBigmodelVo.getRailwayBigmodel());
        if(rows > 0){
            Map<String, String> result = new HashMap<>();
            result.put("id", railwayBigmodelVo.getRailwayBigmodel().getId());
            return AjaxResult.success(result);
        }else {
            return AjaxResult.error();
        }
    }

    /**
     * 上报
     */
    @ApiOperation("上报tlga大模型")
    @PostMapping("/report")
    public AjaxResult report(@RequestBody RailwayBigmodelVo railwayBigmodelVo)
    {
        return toAjax(railwayBigmodelService.report(railwayBigmodelVo));
    }

    /**
     * 删除tlga大模型
     */
    @ApiOperation("删除tlga大模型")
    @GetMapping("del/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        RailwayBigmodel railwayBigmodel = railwayBigmodelService.selectRailwayBigmodelByID(id);
        if(railwayBigmodel.getReportStatus().equals(ReportStatusEnum.SB.getValue())) {
            return AjaxResult.error("已上报，不能删除");
        }
        return toAjax(railwayBigmodelService.deleteRailwayBigmodelByID(id));
    }

    /**
     * 上报
     */
    @ApiOperation("上传附件")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("filePath", fileName);
            ajax.put("fileName", StringUtils.substringAfterLast(fileName, "/"));
            return ajax;
        } catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上报
     */
    @ApiOperation("下载附件")
    @GetMapping("/downloadFile")
    public void resourceDownload(@RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName.replace("/profile/upload/", "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
        }
    }

    /**
     * 导出表格
     * @param response
     * @param railwayBigmodelVo
     */
    @ApiOperation("导出表格")
    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestBody RailwayBigmodelVo railwayBigmodelVo)
    {
        List<RailwayBigmodel> list = railwayBigmodelService.selectRailwayBigmodelListTotal(railwayBigmodelVo);
        for (RailwayBigmodel railwayBigmodel : list) {
            railwayBigmodel.setFileName(StringUtils.substringAfterLast(Optional.ofNullable(railwayBigmodel.getFilePath()).orElse("/"), "/"));
            if(StringUtils.isNotEmpty(railwayBigmodel.getTrainType())) {
                String[] split = railwayBigmodel.getTrainType().split(",");
                List<String> trainArray = new ArrayList<>();
                for (String s : split) {
                    //训练类型  0-预训练 1-二次预训练 2-优化训练
                    if(s.equals("0")){
                        s = "预训练";
                    }else if(s.equals("1")) {
                        s = "二次预训练";
                    } else if (s.equals("2")) {
                        s = "优化训练";
                    }
                    trainArray.add(s);
                }
                railwayBigmodel.setTrainTypeString(String.join(",", trainArray));
            }
            railwayBigmodel.setMobile(railwayBigmodel.getTelephone());
            railwayBigmodel.setUser(railwayBigmodel.getCreateBy());

        }
        ExcelUtil<RailwayBigmodel> util = new ExcelUtil<RailwayBigmodel>(RailwayBigmodel.class);
        util.exportExcel(response, list, "大模型数据");
    }

    /**
     * buju退回
     * @param id
     * @return
     */
    @ApiOperation("删除tlga大模型")
    @GetMapping("/sendBack/{id}")
    public AjaxResult sendBack(@PathVariable String id)
    {
        RailwayBigmodel railwayBigmodel = railwayBigmodelService.selectRailwayBigmodelByID(id);
        if(ObjectUtils.isEmpty(railwayBigmodel)) {
            return AjaxResult.error("该数据不存在");

        }
        if(!railwayBigmodel.getReportStatus().equals(ReportStatusEnum.SB.getValue())) {
            return AjaxResult.error("未上报，不能退回");
        }
        railwayBigmodel.setReportStatus(ReportStatusEnum.TH.getValue());
        return toAjax(railwayBigmodelService.updateRailwayBigmodel(railwayBigmodel));
    }

}
